package com.zth.Controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import com.zth.entity.LayData;
import com.zth.util.ConfugUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController2 {

    @PostMapping("alyFile")
    @ResponseBody
    public LayData uploadFile3(MultipartFile file, HttpServletRequest request) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConfugUtil.END_POINT;
        // oss-cn-beijing.aliyuncs.com
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConfugUtil.ACCESS_SS_ID;
        String accessKeySecret = ConfugUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConfugUtil.BUCKET_NAME;
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

        // 新的名字
        String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
        // 无标题.png  1.3.4.5.jpg
        // +.JPG  PNG JEPG
        // 获取原来的文件的后缀 oldname
        String oldname = file.getOriginalFilename();
        int i = oldname.lastIndexOf(".");
        String suffixname = oldname.substring(i);
        //System.out.println("suffixname = " + suffixname);
        String newname = s + suffixname;
        //System.out.println("newname = " + newname);


        String objectName = newname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 填写字符串。
            String content = "Hello OSS";

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);

            // https://liuhongfei.oss-cn-beijing.aliyuncs.com/a1954baf-78ef-4dab-89f2-82652033ad29.jpg

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String picpath = "https://" + bucketName + "." + endpoint + "/" + objectName;

//        return "index";
        return  new LayData(picpath);
    }


    @PostMapping("file")
    public LayData uploadFile(MultipartFile file, HttpServletRequest request){

        //获取源文件的昵称
        String oldName = file.getOriginalFilename();
        //获取文件后缀的位置
        int i = oldName.lastIndexOf(".");
        //截取后缀
        String substring = oldName.substring(i);
        //1.获取对象
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/upload");
        File file1 = new File(realPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        String UUname = UUID.randomUUID().toString();
        String newName=UUname+substring;
//        System.out.println("原名  = " + oldName);
//        System.out.println("新名字 = " + newName);
//        System.out.println("realPath = " + realPath);

        String newFileName=file1+File.separator+newName;
        File file2 = new File(newFileName);
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String path=newFileName+newName;
        System.out.println("path = " + path);
        LayData layVo = new LayData();
        layVo.setCode(0);
        layVo.setMsg("成功");
        layVo.setData(newFileName);
        return layVo;
    }

}
